package auth_controlle

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"html/template"
	"log"
	"net/http"
	ad "pear-admin-layui-go/app/sys/auth/domain"
	as "pear-admin-layui-go/app/sys/auth/service"
	dls "pear-admin-layui-go/app/sys/dict_list/service"
	urd "pear-admin-layui-go/app/sys/user_role/domain"
	"pear-admin-layui-go/framework/login_filter"
	fr "pear-admin-layui-go/framework/result"
	ft "pear-admin-layui-go/framework/table"
	"strconv"
	"time"
)

func Enable(c *gin.Context) {
	var aer ad.AuthEnableRequest
	_ = c.ShouldBind(&aer)
	user, _ := login_filter.GetCurrentUser(c)
	aer.UpdateTime = time.Now().Unix()
	aer.UpdateBy = user.Id
	aer.UpdateName = user.Username
	db := as.Enable(&aer)
	fr.Result(c, db)
}

func EditPage(c *gin.Context) {
	id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
	code := dls.DictListCode("auth_type")
	auth := as.EditPage(id)
	c.HTML(http.StatusOK, "sys/auth/edit.html", gin.H{
		"authTypes": code,
		"id":        auth.Id,
		"name":      auth.Name,
		"type":      strconv.Itoa(auth.Type),
		"url":       auth.Url,
		"code":      auth.Code,
		"sort":      auth.Sort,
		"icon":      auth.Icon,
		"remark":    auth.Remark,
	})
}

func AddPage(c *gin.Context) {
	pid := c.DefaultQuery("pid", "0")
	code := dls.DictListCode("auth_type")
	c.HTML(http.StatusOK, "sys/auth/add.html", gin.H{
		"authTypes": code,
		"pid":       pid,
	})
}

func Tree(c *gin.Context) {
	user, _ := login_filter.GetCurrentUser(c)
	auths, tx := as.Tree(user.Id)
	log.Println("auths len = ", len(auths))
	if tx.Error != nil {
		fr.Result(c, tx)
	} else {
		tree := ToTree(auths, 0)
		c.JSON(http.StatusOK, tree)
	}
}

func ToTree(auths []urd.UserRoleAuthTreeResponse, pid int64) []map[string]interface{} {
	var tree = make([]map[string]interface{}, 0)
	for i := 0; i < len(auths); i++ {
		v := auths[i]
		if v.Pid == pid {
			tree = append(tree, map[string]interface{}{
				"id":       v.Id,
				"title":    v.Name,
				"icon":     v.Icon,
				"type":     v.Type,
				"href":     v.Url,
				"children": ToTree(auths, v.Id),
			})
		}
	}
	return tree
}

func AuthEdit(c *gin.Context) {
	var aer ad.AuthEditRequest
	_ = c.ShouldBind(&aer)
	user, _ := login_filter.GetCurrentUser(c)
	aer.UpdateTime = time.Now().Unix()
	aer.UpdateBy = user.Id
	aer.UpdateName = user.Username
	db := as.AuthEdit(&aer)
	fr.Result(c, db)
}

func AuthAdd(c *gin.Context) {
	var aar ad.AuthAddRequest
	_ = c.ShouldBind(&aar)
	user, _ := login_filter.GetCurrentUser(c)
	aar.CreateName = user.Username
	aar.CreateTime = time.Now().Unix()
	aar.CreateBy = user.Id
	_, err := as.AuthAdd(&aar)
	fr.Result(c, err)
}

func Auth(c *gin.Context) {
	authTypes := dls.DictListCode("auth_type")
	marshal, _ := json.Marshal(authTypes)
	c.HTML(http.StatusOK, "sys/auth/auth.html", gin.H{
		"authTypes": template.HTML(marshal),
		"enable":    template.HTML("<input type=\"checkbox\" name=\"enable\" value=\"{{d.id}}\" lay-skin=\"switch\" lay-text=\"启用|禁用\" lay-filter=\"power-enable\" {{ d.enable == true ? 'checked' : '' }}/>"),
	})
}

func Table(c *gin.Context) {
	var asr ad.AuthSearchRequest
	_ = c.ShouldBind(&asr)
	auths, count := as.Table(&asr)
	atr := make([]ad.AuthTableResponse, len(auths))
	for i, v := range auths {
		atr[i] = ad.AuthTableResponse{
			Id:         v.Id,
			Pid:        v.Pid,
			Name:       v.Name,
			Url:        v.Url,
			Type:       v.Type,
			Sort:       v.Sort,
			Icon:       v.Icon,
			Code:       v.Code,
			Enable:     v.Enable,
			Remark:     v.Remark,
			CreateTime: v.CreateTime,
			CreateName: v.CreateName,
			UpdateTime: v.UpdateTime,
			UpdateName: v.UpdateName,
		}
	}
	c.JSON(http.StatusOK, ft.TableResponse{
		Count: count,
		Data:  atr,
	})
}
